﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using System.Windows;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Shell;
using Samples.Radio.Agent.Data;
using Samples.Radio.Agent.Model;
using WindowsPhoneAudioStreaming.Audio.Streaming;

namespace Samples.Radio.Agent
{
    public class PlayoutPlayingService : INowPlayingService
    {
        public Repository Repository { get; set; }

        //private const string TileFileName = "/Shared/ShellContent/backgroundart.jpg";

        #region Properties

        public Uri CurrentDataService
        {
            get;
            set;
        }

        public int NumberRecentTracksToDisplay
        {
            get;
            set;
        }

        public DateTime LastUpdated
        {
            get;
            private set;
        }

        /// <summary>
        /// Current playing track
        /// </summary>
        public TrackModel CurrentTrack
        {
            get;
            private set;
        }


        /// <summary>
        /// Recently played tracks
        /// </summary>
        private readonly List<TrackModel> recentTracks = new List<TrackModel>();
        public TrackModel[] RecentTracks
        {
            get { return recentTracks.ToArray(); }
        }


        public PlaylistTrack[] ActiveTrackList
        {
            get;
            set;
        }

        public PlaylistTrack[] QueuedTrackList
        {
            get;
            set;
        }
        #endregion

        #region Constructors
        public PlayoutPlayingService()
        {
            CurrentTrack = new TrackModel();
        }
        #endregion

        #region Methods

        /// <summary>
        /// Get the latest track and update the recent tracks list
        /// </summary>
        public void RefreshCurrentTrack()
        {
            if (CurrentDataService != null && !string.IsNullOrEmpty(CurrentDataService.AbsoluteUri))
            {
                var client = new WebClient();
                client.OpenReadCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                        return;

                    Stream str = e.Result;
                    XDocument nowPlayingXml = XDocument.Load(str);

                    var nowPlayingData = from query in nowPlayingXml.Descendants("item")
                                         select new TrackModel
                                         {
                                             Title = (string)query.Element("title"),
                                             Album = (string)query.Element("album").Element("albumname"),
                                             TrackImageUrl = (string)query.Element("album").Element("albumimage"),
                                             Artist = (string)query.Element("artist").Element("artistname"),
                                             NowPlaying = ((string)query.Element("playing")).ConvertToIsNowPlaying()
                                         };

                    foreach (var track in nowPlayingData)
                    {
                        if (!string.IsNullOrEmpty(track.Title))
                        {
                            if (recentTracks.Count >= NumberRecentTracksToDisplay)
                            {
                                recentTracks.RemoveAt(recentTracks.Count - 1);
                            }

                            if (!recentTracks.Contains(track))
                            {
                                recentTracks.Add(track);
                            }

                            if (track.NowPlaying)
                            {
                                CurrentTrack = track;
                            }

                        }
                    }

                    // close 
                    str.Close();

                    LastUpdated = DateTime.Now;

                    if (TracksUpdated != null)
                    {
                        TracksUpdated(this, null);
                    }

                };
                client.OpenReadAsync(CurrentDataService);
            }
        }

        public void GetCurrentPlaylist()
        { }

        /// <summary>
        /// Create a live tile update
        /// </summary>
        public void UpdateLiveTile(bool includeMusicAndVideoHub=false)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var backgroundImage = new Uri(CurrentTrack.TrackImageUrl, UriKind.Absolute);
                if (CurrentTrack != null && !String.IsNullOrEmpty(CurrentTrack.TrackImageUrl))
                {
                    backgroundImage = new Uri(CurrentTrack.TrackImageUrl, UriKind.Absolute);
                }

                var updatedTile = new StandardTileData
                                      {
                    BackBackgroundImage = backgroundImage,
                    BackTitle = CurrentTrack.Artist, //String.Format("{0} - {1}", this.CurrentTrack.Title, this.CurrentTrack.Artist),
                    BackContent = CurrentTrack.Title
                };

                var primaryTile = ShellTile.ActiveTiles.First();
                primaryTile.Update(updatedTile);

                if (LiveTileUpdated != null)
                {
                    LiveTileUpdated(this, null);
                }
            });

        }

        #endregion

        #region Events
        public event EventHandler TracksUpdated;
        public event EventHandler LiveTileUpdated;
        public void AddTrackToPlaylist(PlaylistTrack track)
        {
            
        }

        #endregion

        public int NumberOfTracks
        {
            get { throw new NotImplementedException(); }
        }

        public AudioTrack TrackByIndex(int trackIndex)
        {
            throw new NotImplementedException();
        }

        public int NextTrackIndex(int currentTrackIndex)
        {
            throw new NotImplementedException();
        }

        public int PreviousTrackIndex(int currentTrackIndex)
        {
            throw new NotImplementedException();
        }

        public void UpdatePlaylist(bool includeMusicAndVideoHub = false)
        {
            throw new NotImplementedException();
        }

        public IPlaybackOptions PlaybackOptions { get { return new StreamOptions(); } }

    }
}
